package cre.sample.test.thread;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MainClass {

	public Map<String, String> firstHashMap = new ConcurrentHashMap<String, String>();

	public void m(String key, String value) {
		firstHashMap.put(key, value);
	}

	public static void main(String[] args) throws InterruptedException {
		for (int i = 0; i < 10; i++) {

			final MainClass m = new MainClass();

			// 线程一
			Thread t1 = new Thread() {
				public void run() {
					for (int i = 0; i < 25; i++) {
						m.m(String.valueOf(i), String.valueOf(i));
					}
				}
			};

			// 线程二
			Thread t2 = new Thread() {
				public void run() {
					for (int j = 25; j < 50; j++) {
						m.m(String.valueOf(j), String.valueOf(j));
					}
				}
			};

			t1.start();
			t2.start();

			// 主线程休眠1秒钟，以便t1和t2两个线程将firstHashMap填装完毕。
			Thread.currentThread().sleep(1000);

			m.m2();
		}
	}

	private void m2() {
		for (int l = 0; l < 50; l++) {
			// 如果key和value不同，说明在两个线程put的过程中出现异常。
			if (!String.valueOf(l).equals(firstHashMap.get(String.valueOf(l)))) {
				System.err.println(String.valueOf(l) + ":" + firstHashMap.get(String.valueOf(l)));
			}
		}
	}

}